axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net';

const tb = document.querySelector('#tb');
const form = document.querySelector('form');

const renderData = function () {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res;
    //console.log(data);

    const html = data
      .map((item) => {
        return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>`;
      })
      .join('');
    //  console.log(html);
    tb.innerHTML = html;
  });
};

renderData();

form.addEventListener('submit', function (e) {
  e.preventDefault();
  const data = serialize(form, { hash: true });
  console.log(data);

  axios.post('/api/addbook', data).then(({ data: res }) => {
    console.log(res);
    alert(res.msg);
    if (res.status !== 201) return;
    renderData();
    // 输完内容为空
    form.reset();
  });
});

//删除 事件委托
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const data = e.target.dataset.id;
    //console.log(data);
    axios.get('/api/delbook?id=' + data).then(({ data: res }) => {
      renderData();
    });
  }
});
